#include "socked.hpp"
#include "DataProcess.hpp"
#include <unistd.h>

class TcpServer
{
public:
    TcpServer()
        : socket_(8888)
    {
    }

    ~TcpServer()
    {
    }

    void init()
    {
        socket_.Socket();
        socket_.Bind();
        socket_.Listen();
    }

    void run()
    {
        while (1)
        {
            socket_.Accept();
            char buf[1024];
            if (fork() == 0)
            {
                close(socket_.sockfd_);
                while (1)
                {
                    int n = read(socket_.lis_sockfd_, buf, sizeof(buf)-1);
                    if (n > 0)
                    {
                        buf[n] = 0;
                        string tem = buf;
                        cout << "<server> get serialize string: " << tem << endl;
                    }
                    else
                        break;
                    string deseri;
                    deserialize(buf, deseri);
                    cout << "<server> send deserialize string: " << deseri << endl;
                    write(socket_.lis_sockfd_, deseri.c_str(), deseri.size());
                }
                exit(0);
            }
            else{
                close(socket_.lis_sockfd_);
            }
        }
    }

private:
    Sock socket_;
};
